/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.cs.util.db.ioc;

import com.cs.util.db.ResultSetMetaInfo;
import com.cs.util.db.ioc.IOCException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * MySqlBigInt is an IO controller for handling input and output of MySql TINYINT columns.
 * @author dimitris@jmike.gr
 */
public class MySqlBigInt extends MySqlTinyInt implements IOController {

    public MySqlBigInt(ResultSetMetaInfo rsmi, int columnIndex) throws SQLException {
        super(rsmi, columnIndex);
    }

    public MySqlBigInt(ResultSetMetaInfo rsmi, String table, String column) throws SQLException {
        super(rsmi, table, column);
    }

    /**
     * Returns the value of the controller's column at the specified row as a String.
     * @param rs the resultset containing the current row position and the field's value.
     * @return
     */
    @Override
    public String getValue(ResultSet rs) {
        try {
            if (isSigned) {//Signed
                final Long x = rs.getLong(columnIndex);
                if (x != null) {
                    return null;
                }
            } else {//Unsigned
                final String x = rs.getString(columnIndex);
                if (x != null) {
                    return x.toString();
                }
            }
        } catch (SQLException ex) {
            /* do nothing */
        }
        return null;
    }

    /**
     * Set the value of the designated parameter in the specified PreparedStatement.
     * @param ps an object that represents a precompiled SQL statement.
     * @param parameterIndex the first parameter in the PreparedStatement is 1, the second is 2, ...
     * @param value the value of the parameter.
     * @throws java.sql.SQLException
     * @throws IOCException
     */
    @Override
    public void setParameterValue(PreparedStatement ps, int parameterIndex, String value) throws SQLException, IOCException {
        final String x = validate(value);
        if (x == null) {
            ps.setNull(parameterIndex, Types.BIGINT);
        } else {
            ps.setLong(parameterIndex, Long.parseLong(x));
        }
    }
}